<?php
namespace app\controller\productAnyShoot;

use app\BaseController;
use app\service\TopviewApiService;
use think\facade\Cache;
use think\facade\Config;

class Template extends BaseController
{
    protected $apiService;

    public function __construct()
    {
        $this->apiService = new TopviewApiService();
    }

    /**
     * 获取模板类目列表
     */
    public function categoryList()
    {
        try {
            // 缓存键
            $cacheKey = 'product_anyshoot_template_category_list';
            
            // 尝试从缓存获取数据
            $data = Cache::get($cacheKey);
            if ($data === null) {
                // 缓存不存在，从API获取数据
                $data = $this->apiService->getProductAnyShootTemplateCategoryList();
                // 从配置文件获取缓存时间
                $cacheTtl = Config::get('topview.cache.template_category_ttl', 3600);
                Cache::set($cacheKey, $data, $cacheTtl);
            }

            return json(['code' => 200, 'msg' => 'success', 'data' => $data]);
        } catch (\Exception $e) {
            return json(['code' => 500, 'msg' => $e->getMessage(), 'data' => null]);
        }
    }

    /**
     * 获取模板列表（从数据库查询）
     */
    public function templateList()
    {
        try {
            $categoryIds = input('categoryIds', '');
            $style = input('style', '');
            
            // 从配置文件获取分页默认值和最大值
            $config = Config::get('topview.product_anyshoot', []);
            $defaultPageSize = $config['default_page_size'] ?? 20;
            $maxPageSize = $config['max_page_size'] ?? 100;
            
            $pageNo = input('pageNo/d', 1);
            $pageSize = input('pageSize/d', $defaultPageSize);
            
            // 限制分页大小
            if ($pageSize > $maxPageSize) {
                $pageSize = $maxPageSize;
            }

            // 验证style参数
            $allowedStyles = $config['allowed_styles'] ?? ['UGC', 'Pro'];
            if (!empty($style) && !in_array($style, $allowedStyles)) {
                return json([
                    'code' => 400, 
                    'msg' => 'style参数只能是' . implode('或', $allowedStyles),
                    'data' => null
                ]);
            }

            // 从数据库查询
            $query = \think\facade\Db::name('product_anyshoot_templates');
            
            // 类目筛选
            if (!empty($categoryIds)) {
                $categoryIdArray = explode(',', $categoryIds);
                $query->whereIn('category_id', $categoryIdArray);
            }
            
            // 风格筛选
            if (!empty($style)) {
                $query->where('style', $style);
            }

            $total = $query->count();
            $list = $query->order('id', 'desc')
                         ->page($pageNo, $pageSize)
                         ->select()
                         ->each(function($item) {
                             // 处理 tags 字段
                             if (!empty($item['tags'])) {
                                 $item['tags'] = json_decode($item['tags'], true);
                             }
                             // 优先使用 OSS 图片地址
                             if (!empty($item['oss_image_url'])) {
                                 $item['templateImageUrl'] = $item['oss_image_url'];
                             } else {
                                 $item['templateImageUrl'] = $item['template_image_url'];
                             }
                             return $item;
                         });

            $data = [
                'total' => $total,
                'pageNo' => $pageNo,
                'pageSize' => $pageSize,
                'data' => $list
            ];
            
            return json(['code' => 200, 'msg' => 'success', 'data' => $data]);
        } catch (\Exception $e) {
            return json(['code' => 500, 'msg' => $e->getMessage(), 'data' => null]);
        }
    }
} 